package com.szholly.data.jdbc;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Date;

import org.springframework.jdbc.core.RowMapper;

import com.szholly.utils.util.DateUtils;
import com.szholly.data.general.RowBase;

/**
 * 定义RowBase的转换
 */
@SuppressWarnings("rawtypes")
public class RowBaseMapper<T extends RowBase> implements RowMapper {

	private Class<T> c;

	public RowBaseMapper(Class<T> c) {
		this.c = c;
	}

	@SuppressWarnings("deprecation")
	@Override
	public T mapRow(ResultSet resultSet, int rowNum) throws SQLException {
		T row = null;
		try {
			row = c.newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		row.setIsNew(false);
		ResultSetMetaData rsmd = resultSet.getMetaData();// rs为查询结果集
		int count = rsmd.getColumnCount();
		for (int i = 1; i <= count; i++) {
			String columnName = rsmd.getColumnName(i);
			Object obj = resultSet.getObject(columnName);
			// 只处理大文本对象，不处理如图片，视频等对象，这些对象都只存储相关路径或相关的ID
			if (obj instanceof byte[]) {
				byte[] data = (byte[]) obj;
				try {
					obj = new String(data, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
					obj = new String(data);
				}
			}
			if (obj instanceof oracle.sql.BLOB) {
				oracle.sql.BLOB blob = (oracle.sql.BLOB) obj;
				InputStream input = blob.getBinaryStream();
				byte[] data = new byte[blob.getBufferSize()];
				try {
					while ((input.read(data)) != -1) {
						input.close();
					}
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				try {
					obj = new String(data, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
					obj = new String(data);
				}
			}
			if (obj instanceof oracle.sql.CLOB) {
				oracle.sql.CLOB clob = (oracle.sql.CLOB) obj;
				Reader is = clob.getCharacterStream();// 得到流
				BufferedReader br = new BufferedReader(is);
				try {
					String s = br.readLine();
					StringBuffer sb = new StringBuffer();
					// 执行循环将字符串全部取出付值给StringBuffer由StringBuffer转成STRING
					while (s != null) {
						sb.append(s);
						s = br.readLine();
						if(s != null){
							sb.append(System.getProperty("line.separator")); // 添加换行符
						}
					}
					obj = sb.toString();
				} catch (IOException e) {
					e.printStackTrace();
					obj = "";
				}
			}
			if (obj instanceof Date) {
				Date dateObjectDate = (Date)obj;
				obj = DateUtils.convertDateTimeToString(dateObjectDate);
			}
			row.put(columnName, obj);
		}
		return row;
	}
}